package com.emm.yixun.system.service.impl.manage;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.mapper.NeedReceiveRefundMapper;
import com.emm.yixun.basic.mapper.SignedMapper;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.DistributionService;
import com.emm.yixun.basic.service.HaveReceiveRefundService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.MsgSettingService;
import com.emm.yixun.basic.service.NeedReceiveRefundService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.basic.service.TransactionRelationService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.HaveReceiveRefund;
import com.emm.yixun.common.model.NeedReceiveRefund;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.TransactionRelation;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.HaveReceiveRefundDto;
import com.emm.yixun.common.model.dto.NeedReceiveRefundDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.dto.TransactionRelationDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.RelationTypeEnum;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.MsgUtil;

@Service("customerNoPaymentNoticeManage")
public class CustomerNoPaymentNoticeManage {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private NoticeService noticeService;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private MsgSettingService msgSettingService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private DistributionService distributionService;
	@Autowired
	private UserService userService;
	@Autowired
	private SysNoticeManage sysNoticeManage;
	@Autowired
	private ProjectSettingService projectSettingService;
	@Autowired
	private NeedReceiveRefundService needReceiveRefundService;
	@Autowired
	private SignedService signedService;
	@Autowired
	private SignedMapper signedMapper;
	@Autowired
	private TransactionRelationService transactionRelationService;

	@Autowired
	private NeedReceiveRefundMapper needReceiveRefundMapper;
	@Autowired
	private HaveReceiveRefundService haveReceiveRefundService;

	/**
	 * 插入消息【逾期未付款】
	 * 
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO createNotice() {
		CommonResDTO resDto = new CommonResDTO();
		resDto.setResult("0");
		try {
			// 获取逾期未付款数据 此方法有误
			// List<Signed> signedList = signedMapper.selectEntityList();
			NeedReceiveRefundDto needReceiveRefundDto = new NeedReceiveRefundDto();
			needReceiveRefundDto.setBusinessType("2");
			needReceiveRefundDto.setDocType("0");
			needReceiveRefundDto.setStatus("1");
			needReceiveRefundDto.setOrders(" t.create_time desc ");
			needReceiveRefundDto.setReceivablesDateAfter(DateUtils.addDay(new Date(), -1));
			List<NeedReceiveRefund> list = needReceiveRefundService.selectListByDto(needReceiveRefundDto);
			if (null == list)
				return resDto;
			// 逾期未付款提醒模板 NT02
			String sendTemp = "客户${customer}已经逾期${day}天未付款，逾期款额${amount}元，请尽快处理或催促付款。";

			// 消息内容模板
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT02");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null)
				sendTemp = dic.getDictionaryName();
			for (NeedReceiveRefund needReceiveRefund : list) {
				Long signedId = needReceiveRefund.getRelationId();
				Signed signed = signedService.selectById(signedId);
				if (null == signed)
					continue;
				// 组装推送消息
				Customer customer = customerService.selectById(signed.getCustomerId());
				if (null == customer)
					continue;
				try {
					// 逾期天数=当天-应收取日期
					Long day = DateUtils.getDaysSub(needReceiveRefund.getReceivablesDate(), new Date());
					// 逾期款额=（每笔应收款金额-已收款金额）
					BigDecimal amount = new BigDecimal(0);

					HaveReceiveRefundDto entity = new HaveReceiveRefundDto();
					entity.setReceivablesId(needReceiveRefund.getId());
					entity.setDocType("0");
					List<HaveReceiveRefund> haveReceiveRefunds = haveReceiveRefundService.selectListByDto(entity);
					if (haveReceiveRefunds != null && haveReceiveRefunds.size() > 0) {
						BigDecimal total = new BigDecimal(0);
						for (HaveReceiveRefund haveReceiveRefund : haveReceiveRefunds) {
							total = total.add(haveReceiveRefund.getRealAmount());
						}
						amount = needReceiveRefund.getTotalReceivablesAmount().subtract(total);
					} else {
						amount = needReceiveRefund.getTotalReceivablesAmount();
					}

					String sendMsg = sendTemp.replace("${customer}", customer.getCustomerName())
							.replace("${day}", day.toString()).replace("${amount}", amount.toString());

					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId", "161");
					noticeParamMap.put("noticeTempType", "NT02");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "逾期未付款提醒");
					noticeParamMap.put("merchantId", String.valueOf(signed.getMerchantId()));
					noticeParamMap.put("projectCode", signed.getProjectCode());
					noticeParamMap.put("userCode", signed.getUserCode());
					noticeParamMap.put("accessCode", signed.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(signed.getCreateUserId()));
					noticeParamMap.put("tempType", "5");

					/*
					 * (ym) 提醒内容增加超链接 start
					 */
					Map<String, String> replaceValuesMap = new HashMap<String, String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, "");
					replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
					replaceValuesMap.put(MsgUtil.BUSINESS_ID, String.valueOf(signed.getId()));
					noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
					/*
					 * (ym) 提醒内容增加超链接 end
					 */
					
					//判断是否已有消息
			    	CommonResDTO common = sysNoticeManage.isRepeated(noticeParamMap);
			    	if("1".equals(common.getResult())){
			    		continue;
			    	}

					// 经纪人
					List<User> userList = new ArrayList<User>();
					TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
					transactionRelationDto.setBusinessId(signed.getId());
					transactionRelationDto.setRelationType(RelationTypeEnum.SIGNED.getNo());
					List<TransactionRelation> transactionRelationList = transactionRelationService
							.selectListByDto(transactionRelationDto);
					if (transactionRelationList.size() > 0) {
						for (int i = 0; i < transactionRelationList.size(); i++) {
							User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
							if (user != null) {
								userList.add(user);
							}
						}
					}
					// 归属人
					if (StringUtils.isNotBlank(customer.getUserCode())) {
						UserDto userDto = new UserDto();
						userDto.setUserCode(customer.getUserCode());
						User user = userService.selectByDto(userDto);
						userList.add(user);
					}

					// 查询营销负责人、案场负责人、销管负责人
					ProjectSettingDto entity_proSetting = new ProjectSettingDto();
					entity_proSetting.setProjectCode(signed.getProjectCode());
					ProjectSetting projectSetting = projectSettingService.selectByDto(entity_proSetting);
					User user_sale, user_field, user_male = null;
					if (projectSetting != null) {
						// if(projectSetting.getSaleLeader() != null){
						// user_sale = userService.selectById(projectSetting.getSaleLeader());//营销负责人
						// userList.add(user_sale);
						// }
						// if(projectSetting.getFieldLeader() != null){
						// user_field = userService.selectById(projectSetting.getFieldLeader());//案场负责人
						// userList.add(user_field);
						// }
						if (projectSetting.getMaLeader() != null) {
							user_male = userService.selectById(projectSetting.getMaLeader());// 销管负责人
							userList.add(user_male);
						}
					}

					// 去重
					Set<User> set = new HashSet<User>(userList);
					userList.clear();
					userList.addAll(set);

					sysNoticeManage.createNoticeWithNoticeTemp(noticeParamMap, userList);
				} catch (Exception e) {
					logger.error("createNotice error: ", e);
				}
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			logger.error("createNotice error: ", e);
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("添加逾期未付款提醒消息失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

}
